package com.test.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class SessionDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //得到session
        HttpSession session = req.getSession();

        //给session中存东西
        session.setAttribute("name","小红");
        String id = session.getId();  //获取sessionId
        //是不是新创建的session
        if(session.isNew()){
            resp.getWriter().write("session create success; sessionId=" + id);
        }else{
            resp.getWriter().write("session 已经存在了 ; sessionId=" + id);
        }
        String name = (String)session.getAttribute("name");
        System.out.println(name);
        session.removeAttribute("name"); //删除session元素
        session.invalidate();  // 注销session
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //
    }
}
